package com.cskaoyan.service.mall;

import com.cskaoyan.bean.PageDataVo;
import com.cskaoyan.bean.mall.order.PageInfoBO;
import com.cskaoyan.bean.mall.brand.Brand;
import com.cskaoyan.bean.mall.brand.BrandExample;
import com.cskaoyan.mapper.mall.BrandMapper;
import com.cskaoyan.utils.Constant;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Repository
@Transactional
public class BrandServiceImpl implements BrandService {
    @Resource
    BrandMapper brandMapper;

    @Override
    public PageDataVo queryBrandInfoList(PageInfoBO pageInfoBO, Integer id, String name) {
        if (pageInfoBO == null) return null;
        PageHelper.startPage(pageInfoBO.getPage(), pageInfoBO.getLimit());
        BrandExample brandExample = new BrandExample();
        brandExample.setOrderByClause(pageInfoBO.getSort() + " " + pageInfoBO.getOrder());
        BrandExample.Criteria criteria = brandExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (id != null) criteria.andIdEqualTo(id);
        if (name != null) criteria.andNameLike("%" + name + "%");
        List<Brand> brands = brandMapper.selectByExample(brandExample);
        return PageDataVo.ok(brands);
    }

    @Override
    public Brand updateBrandInfo(Brand brand) {
        if (brand.getId() == null || brand.getId() <= 0) return null;
        Date date = new Date();
        brand.setUpdateTime(date);
        int i = brandMapper.updateByPrimaryKeySelective(brand);
        if (i == 1) {
            return brandMapper.selectByPrimaryKey(brand.getId());
        }
        return null;
    }

    @Override
    public int deleteBrandInfo(Brand brand) {
        //删除给的deleted是false
        //但是在数据库中0对应false，而数据库中的0为存在，1为不存在
        if (brand.getDeleted()) return Constant.FAIL;
        //将商品brand——id置为0
        brandMapper.updateGoods(brand.getId());
        brand.setDeleted(true);
        int i = brandMapper.updateByPrimaryKeySelective(brand);
        if (i == 1) return Constant.SUCCESS;
        return Constant.FAIL;
    }

    @Override
    public Brand createBrandInfo(Brand brand) {
        brand.setDeleted(false);
        brand.setUpdateTime(new Date());
        brand.setAddTime(new Date());
        brand.setSortOrder((byte) 1);
        int i = brandMapper.insertSelective(brand);
        if (i == 1) return brand;
        return null;
    }

}
